/**
 * Bureaucracy Plugin scripts
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author Andreas Gohr <andi@splitbrain.org>
 * @author     Stephane Chamberland <dokuwiki@meteokid.ca>
 * @date       2009-02-10
 */

buroDatePicker = {
    picker: new Array(),
    texts: false,

    /**
    * Add button action for picker buttons and create picker element
    *
    * @param  DOMElement btn   Button element to add the action to
    * @param  string     edid  ID of the editor textarea
    * @return boolean    If button should be appended
    * @author Gabriel Birke <birke@d-scribe.de>
    */
    addBtnActionPicker: function(edid,opts)
    {
        var btn;
        var input = document.getElementById(edid);
        input.parentNode.appendChild(btn = document.createElement("a"));
        btn.innerHTML = '&nbsp;';
        btn.className = 'date-picker-control';
        this.picker[edid] = new Array();
        this.picker[edid]['id'] = 'picker__'+edid;
        this.picker[edid]['obj'] = buroDatePicker.createPicker(this.picker[edid]['id'],edid,opts);
        eval("btn.onclick = function(){buroDatePicker.showPicker('"+this.picker[edid]['id']+"',this);return false;}");
        return true;
    },

    /**
    * Show a previosly created picker window... actually it toggle the visible state
    *
    * @author Andreas Gohr <andi@splitbrain.org>
    */
    showPicker: function(pickerid,btn){
        var picker;
        //close all pickers, but the selceted one
        for (var edid in this.picker) {
            if(this.picker[edid]['id']!=pickerid){
                picker = document.getElementById(this.picker[edid]['id']);
                picker.style.display = 'none';
            }
        }
        //open selected picker
        picker = document.getElementById(pickerid);
        var x = findPosX(btn);
        var y = findPosY(btn);
        if(picker.style.display == 'none'){

            picker.style.display = 'block';
            picker.style.left = (x+3)+'px';
            picker.style.top = (y+btn.offsetHeight+3)+'px';
        }else{
            picker.style.display = 'none';
        }
    },

    /**
    * Creates a picker window for inserting text
    *
    * The given list can be an associative array with text,icon pairs
    * or a simple list of text. Style the picker window through the picker
    * class or the picker buttons with the pickerbutton class. Picker
    * windows are appended to the body and created invisible.
    *
    * @author Andreas Gohr <andi@splitbrain.org>
    */
    createPicker: function(id,edid,opts){
        var picker = document.createElement('div');
        picker.className = 'datePicker';
        picker.id = id;
        picker.style.position = 'absolute';
        picker.style.display  = 'none';

        this.picker[edid]['dt'] = new Date();

        this.texts = {
            prevMonth: 'Next Month',
            nextMonth: 'Prev Month',
            months: ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],
            days: ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],
            yearTitle: this.picker[edid]['dt'].getFullYear()
        };
        //datePicker.months       = ["January","February","March","April","May","June","July","August","September","October","November","December"];
        //datePicker.fullDay      = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
        //datePicker.titles       = ["Previous month","Next month","Previous year","Next year", "Today", "Show Calendar"];

        this.render(picker,edid);
        this.fill(edid);

        var body = document.getElementsByTagName('body')[0];
        body.appendChild(picker);
        return picker;
    },

    /**
    *
    */
    render: function(oSpan,edid){
        var oT1, oTR1, oTD1, oTH1;
        var oT2, oTR2, oTD2;
        var oMonth, oYear, aCells;

        oSpan.appendChild(oT1 = document.createElement("table"));
        oT1.border = 1;

        oTR1 = oT1.insertRow(oT1.rows.length);
        oTD1 = oTR1.insertCell(oTR1.cells.length);
        oTD1.colSpan = 7;
        //oTD1.className = 'DatePickerHdr';

        oT2 = document.createElement("table");
        oTD1.appendChild(oT2);
        oT2.border = 0;

        oTR2 = oT2.insertRow(oT2.rows.length);

        oTR2.appendChild(oTD2 = document.createElement("th"));
        //oTD2 = oTR2.insertCell(oTR2.cells.length);
        oTD2.title = this.texts.prevMonth;
        oTD2.onclick = function() { this.oDatePicker.onPrev(this); };
        oTD2.oDatePicker = this;
        oTD2.innerHTML = "&lt;&lt;";

        oTR2.appendChild(oTD2 = document.createElement("th"));
        //oTD2 = oTR2.insertCell(oTR2.cells.length);
        oMonth = document.createElement("select");
        oTD2.appendChild(oMonth);
        oMonth.oDatePicker = this;
        oMonth.onchange = oMonth.onkeyup =
            function() { this.oDatePicker.onMonth(this); };
        for ( var i = 0; i < 12; i++ ) {
            oMonth.add(new Option(this.texts.months[i], i),undefined);
        }
        this.picker[edid]['oMonth'] = oMonth;

        oTR2.appendChild(oYear = document.createElement("th"));
        //this.oYear = oTR2.insertCell(oTR2.cells.length);
        oYear.title = this.texts.yearTitle;
        oYear.oDatePicker = this;
        oYear.onclick = function() { this.oDatePicker.onYear(this); };
        this.picker[edid]['oYear'] = oYear;

        oTR2.appendChild(oTD2 = document.createElement("th"));
        //oTD2 = oTR2.insertCell(oTR2.cells.length);
        oTD2.title = this.texts.nextMonth;
        oTD2.onclick = function() { this.oDatePicker.onNext(this); };
        oTD2.oDatePicker = this;
        oTD2.innerHTML = "&gt;&gt;";
        //oTD2.className = 'DatePickerHdrBtn';

        oTR1 = oT1.insertRow(oT1.rows.length);
        for ( i = 0; i < 7; i++ ) {
            oTH1 = document.createElement("th");
            oTH1.appendChild(ooo = document.createElement("span"));
            oTR1.appendChild(oTH1);
            ooo.innerHTML = this.texts.days[i];
            //oTH1.className = 'DatePicker';
            ooo.className = 'fd-day-header';
        }

        aCells = new Array;
        for ( var j = 0; j < 6; j++ ) {
            aCells.push(new Array);
            oTR1 = oT1.insertRow(oT1.rows.length);
            for ( i = 0; i < 7; i++ ) {
                aCells[j][i] = oTR1.insertCell(oTR1.cells.length);
                aCells[j][i].oDatePicker = this;
                aCells[j][i].onclick =
                    function() { this.oDatePicker.onDay(this); };
                aCells[j][i].className ='date-picker-unuset';
            }
        }
        //oSpan.schdatepickacells = this.aCells;
        this.picker[edid]['aCells'] = aCells;
    },

    /**
    *
    */
    fill: function(edid){
        this.clear(edid);
        // place the dates in the calendar
        var nRow = 0;
        var now = new Date();
        var d = new Date(this.picker[edid]['dt'].getTime());
        var m = d.getMonth();

        var aCells = this.picker[edid]['aCells'];

        for ( d.setDate(1); d.getMonth() == m; d.setTime(d.getTime() + 86400000) ) {
            var nCol = d.getDay();
            aCells[nRow][nCol].innerHTML = d.getDate();
            aCells[nRow][nCol].className ='';
            if ( d.getDate() == now.getDate() && d.getMonth() == now.getMonth() && d.getFullYear() == now.getFullYear()) {
                aCells[nRow][nCol].className = 'date-picker-today';
            }
            if ( nCol == 6 ) nRow++;
        }

        // set the month combo
        //this.oMonth.value = m;
        this.picker[edid]['oMonth'].value = m;

        // set the year text
        //this.oYear.innerHTML = this.dt.getFullYear();
        this.picker[edid]['oYear'].innerHTML = this.picker[edid]['dt'].getFullYear();
    },

    /**
    *
    */
    clear: function(edid){
        var aCells = this.picker[edid]['aCells'];
        for ( var j = 0; j < 6; j++ ) {
            for ( var i = 0; i < 7; i++ ) {
                aCells[j][i].innerHTML = "&nbsp;";
                aCells[j][i].className ='date-picker-unused';
            }
        }
    },

    /**
    *
    */
    parentNodeWithID: function(oid){
        if (oid.parentNode){
            var oid2 = oid.parentNode;
            while(!oid2.id && oid2.parentNode) oid2 = oid2.parentNode;
            return oid2;
        }
        return false;
    },

    /**
    *
    */
    edid_from_pickerid: function(p_oid){
        var edid = false;
        for(var id in this.picker){
            if(this.picker[id]['id'] == p_oid) edid = id;
        }
        return edid;
    },

    /**
    *
    */
    onDay: function(oid){
        var p_oid = this.parentNodeWithID(oid);
        var edid = this.edid_from_pickerid(p_oid.id);
        this.picker[edid]['dt'].setDate(oid.innerHTML);
        var dt = this.picker[edid]['dt'];
        var dd = dt.getDate();
        var dd_s = dd.toString();
        if(dd<10) dd_s = '0'+dd_s;
        var mm = dt.getMonth()+1;
        var mm_s = mm.toString();
        if(mm<10) mm_s = '0'+mm_s;
        var yyyy = dt.getFullYear();
        var mystr = '';
        if(dd && mm && yyyy) mystr = yyyy.toString()+'-'+mm_s+'-'+dd_s;
        if(mystr) media2SetValue(edid,mystr);
        p_oid.style.display = 'none';
    },

    /**
    *
    */
    onMonth: function(oid){
        var p_oid = this.parentNodeWithID(oid);
        var edid = this.edid_from_pickerid(p_oid.id);
        //mo=this.oMonth.value;
        var mo=this.picker[edid]['oMonth'].value;
        this.picker[edid]['dt'].setMonth(mo);
        this.fill(edid);
    },

    /**
    *
    */
    onPrev: function(oid){
        var p_oid = this.parentNodeWithID(oid);
        var edid = this.edid_from_pickerid(p_oid.id);
        var mo=this.picker[edid]['dt'].getMonth() -1;
        var yr=this.picker[edid]['dt'].getFullYear();
        //var mo = this.dt.getMonth() -1;
        //var yr = this.dt.getFullYear();
        if(mo<0){
            mo=11;
            yr=yr-1;
        }
        this.picker[edid]['dt'].setMonth(mo);
        this.picker[edid]['dt'].setFullYear(yr);
        this.fill(edid);
    },


    /**
    *
    */
    onNext: function(oid){
        var p_oid = this.parentNodeWithID(oid);
        var edid = this.edid_from_pickerid(p_oid.id);
        var mo=this.picker[edid]['dt'].getMonth() +1;
        var yr=this.picker[edid]['dt'].getFullYear();
        //var mo = this.dt.getMonth() +1;
        //var yr = this.dt.getFullYear();
        if(mo>11){
            mo=0;
            yr=yr+1;
        }
        this.picker[edid]['dt'].setMonth(mo);
        this.picker[edid]['dt'].setFullYear(yr);
        this.fill(edid);
    },

    /**
    *
    */
    onYear: function(oid){
        //yr=this.oYear.value;
        //this.dt.setFullYear(yr);
        //this.fill();
    },

};

/**
* JavaScript functionalitiy for the media management popup
*
* @author Andreas Gohr <andi@splitbrain.org>
*/
media2 = {
    keepopen: false,
    hide: false,
    edid2: new Array(),
    ns2: ':',

    /**
    * Attach the image selector action to all links below the given element
    * also add the action to autofill the "upload as" field
    *
    * @author Andreas Gohr <andi@splitbrain.org>
    */
    selectorattach: function(obj){
        if(!obj) return;

        var items = getElementsByClass('select',obj,'a');
        for(var i=0; i<items.length; i++){
            var elem = items[i];
            elem.style.cursor = 'pointer';
            addEvent(elem,'click',function(event){ return media2.select(event,this); });
        }
    },

    /**
    * Insert the clicked image into the opener's textarea
    *
    * @author Andreas Gohr <andi@splitbrain.org>
    */
    select: function(event,link){
        var id = link.name.substr(2);

        if(!opener){
            // if we don't run in popup display example
            var ex = $('ex_'+id.replace(/:/g,'_'));
            if(ex.style.display == ''){
                ex.style.display = 'none';
            }else{
                ex.style.display = '';
            }
            return false;
        }

        var mystr='';
        var edid = opener.media2.edid2[0];
        var edid_nb = media2.getQueryVariable('media2id');
        if(edid_nb && edid_nb<=opener.media2.edid2.length)
            edid = opener.media2.edid2[edid_nb-1];
        opener.media2SetValue(edid,':'+id);

        if(!media.keepopen) window.close();
        opener.focus();
        return false;
    },

    getQueryVariable: function(variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
            var pair = vars[i].split("=");
            if (pair[0] == variable) {
                return pair[1];
            }
        }
        return false;
    },

    /**
    *
    */
    fillonload: function(edid,ns){
        media2.ns2 = ns;
        media2.edid2.push(edid);
        var textField = document.getElementById(edid);
        if(textField){
            if(textField.value[0]!=':'){
                textField.value = "Click Here to add a file";
                textField.innerHTML = "Click Here to add a file";
            }
            var props = new Array();
            props["url"] = "/exec/lib/exe/mediamanager.php?media2id="+media2.edid2.length+"&ns=";
            props["name"] = "mediaselect";
            props["options"] = "width=750,height=500,left=20,top=20,scrollbars=yes,resizeable=yes";
            props["ns"] = media2.ns2;

            media2addBtnActionMediapopup(textField, props);
        }
    }

};

addInitEvent(function(){
    media2.selectorattach($('media__content'));
});

/**
* Add button action for the mediapopup button
*
* @param  DOMElement btn   Button element to add the action to
* @param  array      props Associative array of button properties
* @return boolean    If button should be appended
* @author Gabriel Birke <birke@d-scribe.de>
*/
function media2addBtnActionMediapopup(btn, props){
    var btn2;
    btn.parentNode.appendChild(btn2 = document.createElement("a"));
    btn2.innerHTML = '&nbsp;';
    btn2.className = 'file-picker-control';
    eval("btn2.onclick = function(){window.open('"+
        jsEscape(props['url']+encodeURIComponent(props['ns']))+"','"+
        jsEscape(props['name'])+"','"+
        jsEscape(props['options'])+
        "');return false;}");

    eval("btn.onclick = function(){window.open('"+
        jsEscape(props['url']+encodeURIComponent(props['ns']))+"','"+
        jsEscape(props['name'])+"','"+
        jsEscape(props['options'])+
        "');return false;}");
    return true;
};
/**
* Set the value of element with id=edid
*/
function media2SetValue(edid,value){
    var textField = document.getElementById(edid);
    if(textField) textField.value = value;
};



/*====
Copied from edit.js
The following function is not needed by the bureaucracy plugin,
but since it is a callback of the medaimanager it needs to exists.
It would be best if the callback was conditional to the function existance (in media.js).
====*/

/**
* Format selection
*
* Apply tagOpen/tagClose to selection in textarea, use sampleText instead
* of selection if there is none. Copied and adapted from phpBB
*
* @author phpBB development team
* @author MediaWiki development team
* @author Andreas Gohr <andi@splitbrain.org>
* @author Jim Raynor <jim_raynor@web.de>
*/
function insertTags(edid,tagOpen, tagClose, sampleText) {
    var txtarea = document.getElementById(edid);
    if(!txtarea) return; /*SCH: added to prevent error on mediamanager call by plugin (return in edid != 'wiki__text'*/
    // IE
    if(document.selection  && !is_gecko) {
        var theSelection = document.selection.createRange().text;
        var replaced = true;
        if(!theSelection){
        replaced = false;
        theSelection=sampleText;
        }
        txtarea.focus();

        // This has change
        var text = theSelection;
        if(theSelection.charAt(theSelection.length - 1) == " "){// exclude ending space char, if any
        theSelection = theSelection.substring(0, theSelection.length - 1);
        r = document.selection.createRange();
        r.text = tagOpen + theSelection + tagClose + " ";
        } else {
        r = document.selection.createRange();
        r.text = tagOpen + theSelection + tagClose;
        }
        if(!replaced){
        r.moveStart('character',-text.length-tagClose.length);
        r.moveEnd('character',-tagClose.length);
        }
        r.select();
    // Mozilla
    } else if(txtarea.selectionStart || txtarea.selectionStart == '0') {
        replaced = false;
        var startPos = txtarea.selectionStart;
        var endPos   = txtarea.selectionEnd;
        if(endPos - startPos){ replaced = true; }
        var scrollTop=txtarea.scrollTop;
        var myText = (txtarea.value).substring(startPos, endPos);
        if(!myText) { myText=sampleText;}
        if(myText.charAt(myText.length - 1) == " "){ // exclude ending space char, if any
        subst = tagOpen + myText.substring(0, (myText.length - 1)) + tagClose + " ";
        } else {
        subst = tagOpen + myText + tagClose;
        }
        txtarea.value = txtarea.value.substring(0, startPos) + subst +
                        txtarea.value.substring(endPos, txtarea.value.length);
        txtarea.focus();

        //set new selection
        if(replaced){
        var cPos=startPos+(tagOpen.length+myText.length+tagClose.length);
        txtarea.selectionStart=cPos;
        txtarea.selectionEnd=cPos;
        }else{
        txtarea.selectionStart=startPos+tagOpen.length;
        txtarea.selectionEnd=startPos+tagOpen.length+myText.length;
        }
        txtarea.scrollTop=scrollTop;
    // All others
    } else {
        var copy_alertText=alertText;
        var re1=new RegExp("\\$1","g");
        var re2=new RegExp("\\$2","g");
        copy_alertText=copy_alertText.replace(re1,sampleText);
        copy_alertText=copy_alertText.replace(re2,tagOpen+sampleText+tagClose);

        if (sampleText) {
        text=prompt(copy_alertText);
        } else {
        text="";
        }
        if(!text) { text=sampleText;}
        text=tagOpen+text+tagClose;
        //append to the end
        txtarea.value += "\n"+text;

        // in Safari this causes scrolling
        if(!is_safari) {
        txtarea.focus();
        }

    }
    // reposition cursor if possible
    if (txtarea.createTextRange){
        txtarea.caretPos = document.selection.createRange().duplicate();
    }
};

